package com.sikao.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sikao.app.R;
import com.sikao.app.adapter.MyTendersAdapter;
import com.sikao.app.bean.Bean;
import com.sikao.app.bean.GetListSubmitBean;
import com.sikao.app.bean.InviteOperateBean;
import com.sikao.app.bean.MyTendersRecordBean;
import com.sikao.app.dao.MyTendersModel;
import com.sikao.app.dao.TenderDeleteModel;
import com.sikao.app.dao.TenderOffShelveModel;
import com.sikao.app.dao.TenderReturnDepositModel;
import com.sikao.app.myinterface.CallbackOne;
import com.sikao.app.net.HttpApi;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.ui.base.BaseActivity;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.utils.Utils;
import com.sikao.app.view.RefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 买家中心我的发布模块
 */
public class MyReleaseTendersActivity extends BaseActivity implements View.OnClickListener {

	private TextView titleTv;
	private ImageView backIv;
	private MyTendersAdapter adapter;
	private MyTendersModel myTendersModel;
	private TenderOffShelveModel tenderOffShelveModel;
	private TenderDeleteModel tenderDeleteModel;
	private TenderReturnDepositModel tenderReturnDepositModel;
	private AlertDialog dialog1, dialog2, dialog3;
	private RefreshListView refreshlistview;
	private GetListSubmitBean bean;
	private InviteOperateBean inviteOperateBean;
	private List<MyTendersRecordBean.ResBean.ListBean> beans;
	private int page = 1;
	private int allPage;
	private int type;//type = 0,首次加载，1代表刷新，2代表加载更多
	private int position;
	private View noData, noNetwork;//无数据和无网络布局

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_my_release_tenders);
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void initData() {
	}

	@Override
	protected void initView() {
		titleTv = (TextView) findViewById(R.id.title_middle_tv);
		backIv = (ImageView) findViewById(R.id.title_left_img);
		refreshlistview = (RefreshListView) findViewById(R.id.refreshlistview);
	}

	@Override
	protected void initListener() {
		backIv.setOnClickListener(this);

		refreshlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				 /*
						（1）、初次进入 1
                        （2）、第二步返回状态 3
                        （3）、查询重新编辑状态3
                        (4)(招标的状态inviteStatus)status:0.1不可编辑; status:-1.2可编辑 ;这是发布招标那边的

                        releaseGoodsState  1，2，3

                        状态为3的时候需要inviteId参数
						 */
				Intent intent = getIntent();
				String inviteId = beans.get(position - 1).getId();
				intent.setClass(MyReleaseTendersActivity.this, ReleaseTenderActivity.class);
				intent.putExtra("inviteId", inviteId);
				Utils.showLog("=====我发布的招标 inviteId:" + inviteId);
				intent.putExtra("releaseInviteState", 3);
				intent.putExtra("inviteStatus", beans.get(position - 1).getStatus());
				startActivity(intent);

			}
		});

		refreshlistview.setOnRefreshListener(new RefreshListView.OnRefreshListener() {
			@Override
			public void onRefresh() {
				page = 1;
				type = 1;
				getList(false);
			}

			@Override
			public void onLoadMore() {
				page++;
				type = 2;
				if (page > allPage) {
					Toast.makeText(MyReleaseTendersActivity.this, "无更多内容", Toast.LENGTH_SHORT).show();
					refreshlistview.onLoadMoreComplete();
				} else {
					getList(false);
				}
			}
		});
	}

	@Override
	protected void init() {
		titleTv.setText("我发布的招标");
		backIv.setVisibility(View.VISIBLE);
		bean = new GetListSubmitBean();
		inviteOperateBean = new InviteOperateBean();
		beans = new ArrayList<>();
		adapter = new MyTendersAdapter(this, beans, new CallbackOne() {
			@Override
			public void notice(String type, int position) {
				MyReleaseTendersActivity.this.position = position;
				if (type.equals("投标记录")) {
					Intent intent = new Intent(MyReleaseTendersActivity.this, TenderBidRecordActivity.class);
					intent.putExtra("bean", beans.get(position).getId());
					startActivity(intent);
				} else if (type.equals("delete")) {
					deleteTender();
				} else if (type.equals("offShelve")) {
					offShelveTender();
				} else {
					returnDeposit();
				}
			}
		});
		refreshlistview.setAdapter(adapter);
		myTendersModel = new MyTendersModel(this, new OnNetBackListener<MyTendersRecordBean>() {
			@Override
			public void netBack(MyTendersRecordBean data) {
				if (type == 1) {
					refreshlistview.onRefreshComplete();
				}
				if (type == 2) {
					refreshlistview.onLoadMoreComplete();
				}
				//无网络
				if (data == null) {
					//清除数据，数据不为空emptyView不会显示
					if (beans.size() != 0) {
						beans.clear();
						adapter.notifyDataSetChanged();
					}
					//如果无数据布局加载过要隐藏掉
					if (noData != null) {
						noData.setVisibility(View.GONE);
					}
					//判断是否加载过无网络布局，避免重复加载显示
					if (noNetwork == null) {
						noNetwork = getLayoutInflater().inflate(R.layout.no_network, null);
						((ViewGroup) refreshlistview.getParent()).addView(noNetwork);
						refreshlistview.setEmptyView(noNetwork);
						Button button = (Button) noNetwork.findViewById(R.id.btn_request);
						button.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								type = 0;
								page = 1;
								getList(true);
							}
						});
					} else {
						noNetwork.setVisibility(View.VISIBLE);
					}
					return;
				}

				if (data.getStatus().equals("1")) {
					allPage = data.getRes().getAllPage();
					if (type != 2 && beans.size() != 0) {
						beans.clear();
					}
					beans.addAll(data.getRes().getList());
					adapter.notifyDataSetChanged();
				} else {
					//无数据
					if (data.getStatus().equals("0")) {
						//清除数据，数据不为空emptyView不会显示
						if (beans.size() != 0) {
							beans.clear();
							adapter.notifyDataSetChanged();
						}
						//如果无网络布局加载过要隐藏掉
						if (noNetwork != null) {
							noNetwork.setVisibility(View.GONE);
						}
						//判断是否加载过无数据布局，避免重复加载显示
						if (noData == null) {
							noData = getLayoutInflater().inflate(R.layout.content_empty, null);
							((ViewGroup) refreshlistview.getParent()).addView(noData);
							refreshlistview.setEmptyView(noData);
							noData.setOnClickListener(new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									type = 0;
									page = 1;
									getList(true);
								}
							});
						} else {
							noData.setVisibility(View.VISIBLE);
						}

					} else {
						Toast.makeText(MyReleaseTendersActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		getList(true);
	}

	private void getList(boolean isShow) {
		bean.setThisPage(page + "");
		bean.setPageNum(HttpApi.LIST_NUMBER);
		myTendersModel.request(JSONUtil.toJSON(bean), isShow);
	}

	private void deleteTender() {
		if (tenderDeleteModel == null) {
			tenderDeleteModel = new TenderDeleteModel(this, new OnNetBackListener<Bean>() {
				@Override
				public void netBack(Bean data) {
					if (data == null) {
						return;
					}
					if (data.getStatus().equals("1")) {
						beans.remove(position);
						adapter.notifyDataSetChanged();
					} else {
						Toast.makeText(MyReleaseTendersActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
		inviteOperateBean.setInviteId(beans.get(position).getId());
		if (dialog1 == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(MyReleaseTendersActivity.this);
			builder.setMessage("确定删除？");
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					tenderDeleteModel.request(JSONUtil.toJSON(inviteOperateBean), true);
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			dialog1 = builder.create();
		}
		dialog1.show();
	}

	private void offShelveTender() {
		if (tenderOffShelveModel == null) {
			tenderOffShelveModel = new TenderOffShelveModel(this, new OnNetBackListener<Bean>() {
				@Override
				public void netBack(Bean data) {
					if (data == null) {
						return;
					}
					if (data.getStatus().equals("1")) {
						beans.get(position).setStatus("3");
						adapter.notifyDataSetChanged();
					} else {
						Toast.makeText(MyReleaseTendersActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
		inviteOperateBean.setInviteId(beans.get(position).getId());
		if (dialog2 == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(MyReleaseTendersActivity.this);
			builder.setMessage("确定下架？");
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					tenderOffShelveModel.request(JSONUtil.toJSON(inviteOperateBean), true);
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			dialog2 = builder.create();
		}
		dialog2.show();
	}

	private void returnDeposit() {
		if (tenderReturnDepositModel == null) {
			tenderReturnDepositModel = new TenderReturnDepositModel(this, new OnNetBackListener<Bean>() {
				@Override
				public void netBack(Bean data) {
					if (data == null) {
						return;
					}
					if (data.getStatus().equals("1")) {
						beans.get(position).setIs_backed(1);
						adapter.notifyDataSetChanged();
					} else {
						Toast.makeText(MyReleaseTendersActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			});
		}
		inviteOperateBean.setInviteId(beans.get(position).getId());
		if (dialog3 == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(MyReleaseTendersActivity.this);
			builder.setMessage("确定退换保证金？");
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					tenderReturnDepositModel.request(JSONUtil.toJSON(inviteOperateBean), true);
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			dialog3 = builder.create();
		}
		dialog3.show();
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.title_left_img:
				finish();
				break;
			default:
				break;
		}
	}
}
